package org.microservice.system.controller;

import org.apache.commons.lang.StringUtils;
import org.microservice.common.base.BaseControllerImpl;
import org.microservice.common.bean.MenuVo;
import org.microservice.common.util.AuthUtil;
import org.microservice.common.util.R;
import org.microservice.common.util.TreeUtil;
import org.microservice.system.dao.SysMenuDao;
import org.microservice.system.service.SysMenuService;
import org.microservice.system.utils.dto.MenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/20
 * Time: 15:55
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@RestController
@RequestMapping("/menu")
public class SysMenuController extends BaseControllerImpl<SysMenuDao,MenuVo> {


    @Autowired
    private SysMenuService sysMenuService;

    /**查询用户的菜单树
     * @RequestParam("userName") String userName,
     @RequestParam("menuType") Integer[] menuType, @RequestParam("isTree") boolean isTree
     * @return
     */
    @PostMapping("/getMenuByUserName")
    public R getMenuByUserName(@RequestBody Map<String ,Object> params){

        String userName = (String) params.get("userName");
        String type = (String) params.get("menuType");
        String[] menuType = StringUtils.isBlank(type)?null:type.split(",");

        Boolean isTree = (Boolean) params.get("isTree");
        List<MenuTree> menus = sysMenuService.getMenuTreeByUserNameAndMenuType(userName, menuType,isTree);
        return R.ok().put("data",menus).put("perms",AuthUtil.getAuthorities());
    }

    /**
     * 查询角色的菜单树
     * @param id
     * @return
     */
    @GetMapping("/getMenusTreeByRoleId")
    public R getMenusTreeByRoleId(@RequestParam(value = "roleId") int id){
        List<MenuVo> menuVos =sysMenuService.getMenusByRoleId(id);
        List<MenuTree> menuTreeList = new ArrayList<>();
        menuVos.forEach(menuVo -> {
            menuTreeList.add(new MenuTree(menuVo));
        });
        return R.ok().put("data", TreeUtil.bulid(menuTreeList,0));
    }


    public R getListPage(@RequestBody Map<String,Object> params){
        List<MenuTree> menuVos = sysMenuService.getMenuListPage(params);
        return R.ok().put("data",menuVos);
    }


    @PostMapping("/save")
    public R save(@RequestBody MenuVo menuVo){
        return  sysMenuService.save(menuVo);
    }

    /**
     * 禁用启用菜单
     * @param id
     * @param disabled
     * @return
     */
    @GetMapping("/disabledOrEnabled")
    public R disabledOrEnabled(@RequestParam(value = "id") int id,@RequestParam(value = "disabled") boolean disabled){
        sysMenuService.disabledOrEnabledById(id,disabled);
        return R.ok();
    }




}
